package edu.ptu.communityplatform.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.http.HttpServletResponse;


/**
 * @BelongsProject: communityPlatform
 * @BelongsPackage: edu.ptu.communityplatform.utils
 * @Author: HYJ
 * @CreateTime: 2025-04-05  02:19
 * @Description: 响应工具类，用于将对象序列化为JSON并写入HttpServletResponse
 * @Version: 1.0
 */

public class ResponseUtil {
    /**
     * 将对象转换为JSON格式并写入响应
     *
     * @param resp   HttpServletResponse对象，用于设置响应头和输出内容
     * @param object 需要序列化的对象
     * @throws Exception 可能抛出IOException或JSON处理相关的异常
     */

    public static void toResponse(HttpServletResponse resp, Object obj) throws Exception {
        // 设置响应头为JSON格式
        resp.setContentType("application/json;charset=utf-8");

        // 将对象序列化为JSON并写入响应
        resp.getWriter().write(
                new ObjectMapper().writeValueAsString(obj)
        );

    }
}
